package com.example.springboot3005web.controller;

import com.example.springboot3005web.vo.ArticleVo;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ArticleController {

    @PostMapping("/article/add")
    public Map<String,Object> addArticle(@Validated(value = {ArticleVo.AddArticleGroup.class}) @RequestBody ArticleVo articleVo,
                                         BindingResult br){

        Map<String,Object> map = new HashMap<>();
        if( br.hasErrors() ){
            List<FieldError> fieldErrors = br.getFieldErrors();
            for (int i = 0; i < fieldErrors.size(); i++) {
                FieldError fieldError = fieldErrors.get(i);
                map.put(i+"-"+fieldError.getField(),fieldError.getDefaultMessage());
            }
        }

        return map;
    }

    @PostMapping("/article/edit")
    public Map<String,Object> EditArticle(@Validated(value = {ArticleVo.EditArticleGroup.class}) @RequestBody ArticleVo articleVo,
                                         BindingResult br){

        Map<String,Object> map = new HashMap<>();
        if( br.hasErrors() ){
            List<FieldError> fieldErrors = br.getFieldErrors();
            for (int i = 0; i < fieldErrors.size(); i++) {
                FieldError fieldError = fieldErrors.get(i);
                map.put(i+"-"+fieldError.getField(),fieldError.getDefaultMessage());
            }
        }

        return map;
    }

}

